package org.nutz.boot.starter.javamelody;

import net.bull.javamelody.JdbcWrapper;
import net.bull.javamelody.MonitoringFilter;
import net.bull.javamelody.Parameter;
import net.bull.javamelody.SessionListener;
import org.nutz.boot.starter.WebEventListenerFace;
import org.nutz.boot.starter.WebFilterFace;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.EnumSet;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Map;

@IocBean(create = "init")
public class JavamelodyFilterStarter implements WebFilterFace, WebEventListenerFace {

    @Inject("refer:$ioc")
    protected Ioc ioc;

    @Inject
    protected PropertiesProxy conf;

    @Override
    public String getName() {
        return "javamelody";
    }

    @Override
    public String getPathSpec() {
        return conf.get("javamelody.path-spec", "/*");
    }

    @Override
    public EnumSet<DispatcherType> getDispatches() {
        return EnumSet.of(
                DispatcherType.REQUEST,
                DispatcherType.FORWARD,
                DispatcherType.INCLUDE,
                DispatcherType.ASYNC,
                DispatcherType.ERROR
        );
    }

    @IocBean(name = "javamelodyFilter")
    public MonitoringFilter createNutFilter() {
        return new MonitoringFilter();
    }

    @Override
    public Filter getFilter() {
        return ioc.get(MonitoringFilter.class, "javamelodyFilter");
    }

    @Override
    public Map<String, String> getInitParameters() {
        Map<String, String> paramsMap = new HashMap<>();
        for (Parameter parameter : Parameter.values()) {
            String configKey = "javamelody." + parameter.getCode();
            String configValue = conf.get(configKey);
            if (!Strings.isEmpty(configValue)) {
                paramsMap.put(configKey, configValue);
            }
        }
        return paramsMap;
    }

    @IocBean(name = "javamelodyListener")
    public EventListener createNutListener() {
        return new SessionListener();
    }

    @Override
    public EventListener getEventListener() {
        return ioc.get(SessionListener.class, "javamelodyListener");
    }

    public void init() {
        DataSource dataSource = ioc.get(DataSource.class);
        if (dataSource != null) {
            JdbcWrapper.registerSpringDataSource("dataSource", dataSource);
        }
    }
}
